//获取应用实例
var app = getApp();
var reLoginNum = 0;

// 初始化数据
var init = {

  // 数据
  data: {

    // 优惠码
    selectCouponSn: '',

    //是否使用积分
    usePoints: 0,

    // 是否显示优惠券列表
    showCoupon: false,

    // 订单总金额
    totalAmount: 0
  },

  // 页面第一次加载
  onLoad: function (options) {
    console.log(options);
    var that = this;
    that.setData({
      options: options
    })

    // 登录授权
    app.getLoginSession(function (session) {
      that.getData(session);
    })
  },

  // 获取数据
  getData: function (session) {

    var that = this;
    var options = that.data.options;
    var params = {};


    console.log(options);

    if (options.fromcart && options.fromcart == 1) {// 购物车立即结算
      params = {
        app: 'order',
        goods: 'cart',
        checked_goods: options.checked_goods,
        fromcart: options.fromcart,
        t_session: session
      }
    } else { // 详情页立即购买
      params = {
        app: 'order',
        act: 'buynow',
        goods: 'buynow',
        goods_id: options.goodsId || options.goods_id,
        spec_id: options.spec_id,
        quantity: options.quantity,
        t_session: session,
        use_insurance: options.use_insurance
      }
    }

    console.log(params);

    // 创建来源页面参数，让选择地址后可以返回
    var referer = '';
    for (var i in params) {
      referer += '&' + i + '=' + params[i]
    }

    // 请求前
    that.setData({

      // 来源参数
      referer: '?' + referer.substr(1) + '&from=' + 'confirmOrder' + (options.formCart ? '&fromCart=' + options.fromCart : ''),

      // 开启loading
      loading: true
    });

    console.log(that.data.referer);

    // 请求
    wx.request({

      // 请求地址
      url: app.api,

      // 请求参数
      data: params,

      // 请求成功
      success: function (res) {
        var data = res.data;
        console.log(data.retval);
        if (data.done) {

          that.setData({
            data: data.retval,

            // 保存订单原始总价
            totalAmount: data.retval.goods_info.amount,

            // 关闭loading效果
            loading: false
          })

        } else {

          // 检查是否登录失败
          if (data.reLogin && (reLoginNum <= app.reLoginNum)) {
            app.login(function (session) {
              that.getData(that.data.options, session);
            });
            reLoginNum++;
          } else {
            that.setData({
              errorTips: data.msg || '请求错误，act：buynow'
            })
          }
        }

      },

      // 请求失败
      fail: function () {
        that.setData({
          errorTips: '接口请求失败，act：buynow'
        })
      }
    });

  },

  // 使用积分
  usePoints: function () {
    var that = this;
    that.setData({
      usePoints: that.data.usePoints == 0 ? 1 : 0,
      'data.goods_info.amount': (function () {
        if (that.data.usePoints == 0) {
          var newAmount = (parseFloat(that.data.totalAmount) - parseFloat(that.data.data.integral_money)).toFixed(2);
          return newAmount > 0 ? newAmount : 0
        } else {
          return that.data.totalAmount
        }
      })()
    });

  },

  // 显示优惠券列表
  showCoupon: function () {
    var that = this;
    that.setData({
      showCoupon: !that.data.showCoupon
    })
  },

  // 选择优惠券
  selectCouponSn: function (event) {
    console.log(event.currentTarget.dataset.sn);
    var that = this;
    var sn = event.currentTarget.dataset.sn;
    var price = event.currentTarget.dataset.price;
    that.setData({
      selectCouponSn: sn,
      showCoupon: !that.data.showCoupon,
      limitPrice: price,
      'data.goods_info.amount': (parseFloat(that.data.totalAmount) - parseFloat(price)).toFixed(2)
    })
  },

  // 添加留言
  msg: function (event) {
    this.setData({
      msg: event.detail.value
    })
  },

  // 确认提交
  submit: function () {
    var that = this;
    var options = that.data.options;
    var data = that.data.data;
    app.getLoginSession(function (session) {

      var params = {};
      var api = app.api;
      if (data.addresses.length==0){
        wx.showModal({
          title: '提示',
          content: '请选择收货地址',
        })
      }else{
        if (options.fromcart && options.fromcart == 1) {// 购物车立即结算

          var checkedGoods = [];
          for (var i = 0; i < data.goods_info.goods.length; i++) {
            checkedGoods.push(data.goods_info.goods[i].goods_id + '_' + data.goods_info.goods[i].spec_id)
          }

          params = {
            app: 'order',
            goods: 'cart',
            checked_goods: checkedGoods.join(),
            mall_coupon: that.data.selectCouponSn,
            use_integral: that.data.usePoints,
            my_address: data.addresses[0].addr_id,
            order_token: data.order_token,
            message: that.data.msg || '',
            t_session: session
          }
        } else { // 详情页立即购买 （参数部分得写在地址上）
          api += '?app=order&act=buynow&goods=buynow&goods_id=' + data.goods_info.goods[0].goods_id + '&quantity=' + data.goods_info.goods[0].quantity + '&spec_id=' + data.goods_info.goods[0].spec_id + '&use_insurance=' + options.use_insurance;
          params = {
            //app: 'order',
            //goods: 'buynow',
            //act: 'buynow',
            mall_coupon: that.data.selectCouponSn,
            use_integral: that.data.usePoints,
            my_address: data.addresses && data.addresses.length > 0 ? data.addresses[0].addr_id : '',
            order_token: data.order_token,
            message: that.data.msg || '',
            t_session: session
          }
        }

        // 生成订单号
        wx.showLoading({
          title: '确认中...'
        });

        // 请求
        wx.request({

          // 请求地址
          url: api,

          // 请求参数
          data: params,

          // 请求头
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },

          // 请求方法（后端根据method来判断是提交还是确认）
          method: 'POST',

          // 请求成功
          success: function (res) {
            console.log(res.data);
            var data = res.data;
            var amount = that.data.data.goods_info.amount; // 金额大于0才能支付
            app.callToPay(data.retval.order_id, amount);
            wx.hideLoading();
          }
        })
      }
      

    })
  }

};

// 注册页面
Page(init);
